package com.gtenacg.cartoonservice.controller;

import com.gtenacg.cartoonservice.common.annotation.CheckToken;
import com.gtenacg.cartoonservice.common.Const;
import com.gtenacg.cartoonservice.common.Result;
import com.gtenacg.cartoonservice.pojo.model.NovelType;
import com.gtenacg.cartoonservice.service.NovelTypeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/novelType")
@RequiredArgsConstructor
public class NovelTypeController {

    final NovelTypeService novelTypeService;

    @GetMapping
    public Result<List<NovelType>> search(
            @RequestParam(required = false) String name
    ) {
        log.info("获取电子书类型列表, name:{}", name);
        List<NovelType> list = novelTypeService.search(name);
        return Result.success(list);
    }

    @GetMapping("/list")
    public Result<List<NovelType>> list() {
        log.info("获取电子书类型列表");
        List<NovelType> list = novelTypeService.list();
        return Result.success(list);
    }

    @CheckToken
    @PostMapping
    public Result<Integer> insert(@RequestBody NovelType novelType) {
        log.info("新增电子书类型: {}",novelType);
        Integer id = null;
        try {
            id = novelTypeService.insert(novelType);
        } catch (DuplicateKeyException e) {
            return new Result<>(HttpStatus.CONFLICT.value(), Const.DUPLICATE_KEY,null);
        }
        return Result.success(id);
    }

    @CheckToken
    @PutMapping
    public Result<Void> update(@RequestBody NovelType novelType) {
        log.info("更新电子书类型: {}",novelType);
        novelTypeService.update(novelType);
        return Result.success();
    }

    @CheckToken
    @DeleteMapping("/{ids}")
    public Result<Void> delete(@PathVariable List<Integer> ids) {
        novelTypeService.delete(ids);
        return Result.success();
    }
}
